package cn.mesmile.grpc.client;

import cn.mesmile.grpc.demo.Greeting;
import cn.mesmile.grpc.demo.HelloWorldServiceGrpc;
import cn.mesmile.grpc.demo.Person;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author zb
 * @date 2021/1/3 11:51
 * @Description:
 */
@Slf4j
@Component
public class HelloWorldClient {


    private HelloWorldServiceGrpc.HelloWorldServiceBlockingStub helloWorldServiceBlockingStub;

    @PostConstruct
    private void init() {

        ManagedChannel managedChannel = ManagedChannelBuilder
                .forAddress("localhost", 6565).usePlaintext().build();

        helloWorldServiceBlockingStub = HelloWorldServiceGrpc.newBlockingStub(managedChannel);
    }

    public Greeting sayHello(String firstName, String lastName, List<String> nameList) {

        Person.Builder builder = Person.newBuilder();
        builder .setLastName(lastName);
        for (String name : nameList) {
            builder.addNameList(name);
        }
        Person person = builder.build();

        log.info("client sending {}", person);

        Greeting greeting = helloWorldServiceBlockingStub.sayHello(person);
        log.info("client received {}", greeting);

        return greeting;
    }

}
